﻿using Microsoft.CSharp;
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 代码编译可执行程序
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string code = """
                using System;
                using System.IO;
                namespace HelloWorld
                {
                    class HelloWorldClass
                    {
                        static void Main(string[] args)
                        {
                            Console.WriteLine("Hello World!");
                            File.WriteAllText("test.txt","写入成功");
                            Console.ReadLine();
                        }
                    }
                }
                """;

            // 创建CodeDomProvider实例
            CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");

            System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
            parameters.GenerateExecutable = true;
            parameters.OutputAssembly = "2.exe";//生成执行程序路径
            CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, code);//开始编译

            Console.ReadKey();
        }

    }
}
